package top.huxy.boot.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

/**
 * @Classname ControllerTimeConsume
 * @Description 开发使用，记录方法执行耗时，以日志方式记录信息
 * @Date 2021/8/29 21:30
 * @Created by huxy
 */
@Aspect
@Component
@Slf4j
@ConditionalOnProperty(name = "spring.profiles.active",havingValue = "dev")
public class ControllerTimeConsume {

    @Pointcut("execution(* top.huxy.boot.controller..*.*(..)) || " +//所有控制器
            "@annotation(top.huxy.boot.annotation.ListeningExcutionTime) || " +//所有有这个注解的方法
            "@within(top.huxy.boot.annotation.ListeningExcutionTime)")//所有有这个注解的方法中的所有类
    public void timePointcut() {
    }

    @Around("timePointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Object result;
        String methodName = joinPoint.getSignature().getName();
        String className = joinPoint.getTarget().getClass().getName();
        long time_start = System.currentTimeMillis();
        try {
            result = joinPoint.proceed();
        } finally {
            long time_end = System.currentTimeMillis();
            log.info("执行方法:{},耗时:{}ms", className + "." + methodName + "()", (time_end - time_start));
        }

        return result;
    }
}
